{% extends 'base.html' %}
{% load static %}

{% block title %}与{{ other_user.username }}的对话 - 本地有约{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="row">
        <div class="col-lg-8 mx-auto">
            <!-- 对话头部 -->
            <div class="card mb-4">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <a href="{% url 'location:message_list' %}" class="btn btn-outline-secondary me-3">
                            <i class="fas fa-arrow-left"></i>
                        </a>
                        <img src="{{ other_user.avatar.url|default:'/static/images/default-avatar.jpg' }}"
                             class="rounded-circle me-3" width="50" height="50" alt="头像">
                        <div class="flex-grow-1">
                            <h5 class="mb-1">{{ other_user.username }}</h5>
                            <div class="text-muted small">
                                {% if other_user.profile.occupation %}
                                <span class="me-3"><i class="fas fa-briefcase me-1"></i>{{ other_user.profile.occupation }}</span>
                                {% endif %}
                                <span><i class="fas fa-clock me-1"></i>最后活跃 2小时前</span>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                                <i class="fas fa-ellipsis-h"></i>
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="{% url 'location:user_profile' other_user.id %}">
                                    <i class="fas fa-user me-2"></i>查看主页
                                </a></li>
                                <li><a class="dropdown-item" href="#">
                                    <i class="fas fa-ban me-2"></i>屏蔽用户
                                </a></li>
                                <li><a class="dropdown-item text-danger" href="#">
                                    <i class="fas fa-flag me-2"></i>举报用户
                                </a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 消息列表 -->
            <div class="card mb-4">
                <div class="card-body" style="height: 500px; overflow-y: auto;" id="messagesContainer">
                    {% for message in messages %}
                    <div class="message-item mb-3 {% if message.sender == user %}text-end{% endif %}">
                        <div class="d-flex {% if message.sender == user %}justify-content-end{% endif %}">
                            {% if message.sender != user %}
                            <img src="{{ message.sender.avatar.url|default:'/static/images/default-avatar.jpg' }}"
                                 class="rounded-circle me-2" width="32" height="32" alt="头像">
                            {% endif %}

                            <div class="message-bubble {% if message.sender == user %}bg-primary text-white{% else %}bg-light{% endif %}"
                                 style="max-width: 70%; border-radius: 18px; padding: 12px 16px;">
                                <div class="message-content">
                                    {{ message.content|linebreaks }}
                                </div>
                                <div class="message-time small {% if message.sender == user %}text-white-50{% else %}text-muted{% endif %} mt-1">
                                    {{ message.created_at|time }}
                                    {% if message.is_read and message.sender == user %}
                                    <i class="fas fa-check ms-1"></i>
                                    {% endif %}
                                </div>
                            </div>

                            {% if message.sender == user %}
                            <img src="{{ message.sender.avatar.url|default:'/static/images/default-avatar.jpg' }}"
                                 class="rounded-circle ms-2" width="32" height="32" alt="头像">
                            {% endif %}
                        </div>
                    </div>
                    {% empty %}
                    <div class="text-center py-5">
                        <i class="fas fa-comments fa-2x text-muted mb-3"></i>
                        <p class="text-muted">还没有消息，开始对话吧！</p>
                    </div>
                    {% endfor %}
                </div>
            </div>

            <!-- 消息发送表单 -->
            <div class="card">
                <div class="card-body">
                    <form id="messageForm" onsubmit="sendMessage(event, {{ other_user.id }})">
                        {% csrf_token %}
                        <div class="input-group">
                            <textarea class="form-control" id="messageContent" name="content"
                                      rows="2" placeholder="输入消息..." required></textarea>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </div>
                        <div class="mt-2 d-flex justify-content-between align-items-center">
                            <small class="text-muted">按 Enter 发送，Shift + Enter 换行</small>
                            <small class="text-muted" id="charCount">0/1000</small>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const messagesContainer = document.getElementById('messagesContainer');
    const messageContent = document.getElementById('messageContent');
    const charCount = document.getElementById('charCount');

    // 滚动到底部
    scrollToBottom();

    // 字符计数
    messageContent.addEventListener('input', function() {
        charCount.textContent = `${this.value.length}/1000`;
    });

    // 快捷键支持
    messageContent.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            document.getElementById('messageForm').dispatchEvent(new Event('submit'));
        }
    });
});

function scrollToBottom() {
    const container = document.getElementById('messagesContainer');
    container.scrollTop = container.scrollHeight;
}

async function sendMessage(event, receiverId) {
    event.preventDefault();

    const form = event.target;
    const content = form.content.value.trim();

    if (!content) return;

    try {
        const formData = new FormData(form);
        formData.append('receiver_id', receiverId);

        const response = await fetch('/location/social/messages/send/', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        const result = await response.json();

        if (result.status === 'success') {
            form.reset();
            document.getElementById('charCount').textContent = '0/1000';

            // 重新加载页面以显示新消息
            location.reload();
        } else {
            alert('发送失败：' + result.message);
        }
    } catch (error) {
        alert('发送失败：网络错误');
        console.error('Error:', error);
    }
}

// 定期检查新消息（可选功能）
setInterval(() => {
    // 这里可以实现实时消息更新
}, 30000);
</script>

<style>
.message-bubble {
    position: relative;
    word-wrap: break-word;
}

.message-bubble.bg-primary {
    border-bottom-right-radius: 4px !important;
}

.message-bubble.bg-light {
    border-bottom-left-radius: 4px !important;
}

#messagesContainer {
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.message-item:last-child {
    margin-bottom: 0 !important;
}

.form-control {
    border-radius: 20px;
    resize: none;
}

.btn {
    border-radius: 20px;
}
</style>
{% endblock %}